import pygame
from constants import *
from game import Game
from ai import AI
from bullet import Bullet

def main():
    # 初始化Pygame
    pygame.init()

    # 创建游戏窗口
    screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption("坦克大战")

    # 创建游戏实例
    game = Game()
    ai = AI(game.enemy, game.player)

    # 游戏主循环
    running = True
    clock = pygame.time.Clock()

    while running:
        # 事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and game.game_over:
                    # 重新开始游戏
                    game.reset_game()
                    ai = AI(game.enemy, game.player)

        # 处理玩家输入
        game.handle_player_input()

        # 更新AI
        if not game.game_over or (game.post_game_state == "enemy_win"):
            ai_fire = ai.update() and not game.game_over  # 只有在游戏未结束时才允许敌方发射炮弹

            # 如果敌方坦克需要发射炮弹
            if ai_fire:
                bullet_pos = game.enemy.fire()
                if bullet_pos:
                    x, y, angle = bullet_pos
                    game.bullets.append(Bullet(x, y, angle, is_player_bullet=False))
                    game.stats['enemy']['shots'] += 1

        # 更新游戏状态
        game.update()

        # 填充背景色
        screen.fill(BACKGROUND_COLOR)

        # 绘制游戏元素
        game.draw(screen)

        # 更新显示
        pygame.display.flip()

        # 控制游戏帧率
        clock.tick(60)

    pygame.quit()

if __name__ == "__main__":
    main()